const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads/avatars');
console.log('上传目录:', uploadDir);

if (!fs.existsSync(uploadDir)) {
  console.log('创建上传目录...');
  fs.mkdirSync(uploadDir, { recursive: true });
  console.log('上传目录已创建');
}

// 配置存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log('文件上传目标目录:', uploadDir);
    console.log('上传的文件:', file);
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 使用时间戳+用户ID+原始扩展名生成文件名
    const uniqueSuffix = Date.now() + '-' + req.user._id;
    const ext = path.extname(file.originalname);
    const filename = 'avatar-' + uniqueSuffix + ext;
    console.log('生成的文件名:', filename);
    cb(null, filename);
  }
});

// 文件过滤器 - 只允许图片
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型，只允许 jpg, jpeg, png 和 gif'), false);
  }
};

// 创建上传中间件
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制为5MB
  },
  fileFilter: fileFilter
});

module.exports = { upload }; 